﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Xml;
using VBModel;

namespace VBBLL
{
    public class BookBll
    {

        //传递到WorkFlow
        public string startApprove(string applicant, string weburl, string leadship)
        {
            workflowSrv.WFWebserviceClient wfb = new workflowSrv.WFWebserviceClient();
            string xml = createXml(applicant, weburl, leadship);
            string erro = string.Empty;
            string sguid = wfb.StartWF(33300000, xml, null, out erro);
            if (sguid == string.Empty)
            {
                return "审批流开启失败";
            }
            return sguid;
        }

        public string createXml(string applicant, string weburl, string leadship)
        {
            return GenerateXMLFile(applicant, weburl, leadship);
        }
        public string GenerateXMLFile(string applicant, string weburl, string leadship)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                //根节点
                XmlElement rootElement = xmlDoc.CreateElement("EFlowsConfigXML");
                xmlDoc.AppendChild(rootElement);
                //第一层第一个
                XmlElement firstLevelElemet1 = xmlDoc.CreateElement("WFParameters");
                firstLevelElemet1.SetAttribute("Description", "运行时候的配置参数");
                rootElement.AppendChild(firstLevelElemet1);
                //第二层第一个
                XmlElement secondLevelElemet1 = xmlDoc.CreateElement("WFParameter");
                //secondLevelElemet1.SetAttribute("Description", "申请人");
                secondLevelElemet1.SetAttribute("name", "WFApplyBy");
                secondLevelElemet1.SetAttribute("Value", applicant);
                firstLevelElemet1.AppendChild(secondLevelElemet1);
                //第二层第二个
                XmlElement secondLevelElemet2 = xmlDoc.CreateElement("WFParameter");
                //secondLevelElemet2.SetAttribute("Description", "审批内容页面链接URL");
                secondLevelElemet2.SetAttribute("name", "WFContentURL");
                secondLevelElemet2.SetAttribute("Value", weburl);
                firstLevelElemet1.AppendChild(secondLevelElemet2);
                //第一层第二个
                XmlElement firstLevelElemet2 = xmlDoc.CreateElement("StaticColumns");
                //firstLevelElemet2.SetAttribute("Description", "用于查询检索的列");
                rootElement.AppendChild(firstLevelElemet2);
                XmlElement secondLevelElemet3 = xmlDoc.CreateElement("StaticColumn");
                secondLevelElemet3.SetAttribute("name", "LeaderShip");
                secondLevelElemet3.SetAttribute("Value", leadship);
                firstLevelElemet2.AppendChild(secondLevelElemet3);
            }
            catch (Exception ex)
            {
                Worker.writeErrorMessage("0", ex, "createXml");
            }
            return xmlDoc.InnerXml;
        }

        public string checkOnceWithPeriodicConflict(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime)
        {
            DateTime sd = DateTime.Parse(startDate);
            DateTime ed = DateTime.Parse(endDate);
            using (var mme = new VenueBookingTestEntities())
            {
                //查询出所有的在本次会议开始后才结束的会议预定
                var query = (from bm in mme.MTR_bas_BookingManage
                             join bs in mme.MTR_bas_BookingSchedul
                                 on bm.bookingID equals bs.planId
                             where bm.Meetingroom == meetingRoomNo && (bm.bookingState == 1 || bm.bookingState == 2) && bs.isPeriodic == true
                             && bs.meetingEndDate >= sd
                             select new
                             {
                                 ssd = bs.meetingStartDate,
                                 sst = bs.startTime,
                                 sed = bs.meetingEndDate,
                                 set = bs.endTime,
                                 Monday = bs.Monday,
                                 Tuesday = bs.Tuesday,
                                 Wednesday = bs.Wednesday,
                                 Thursday = bs.Thursday,
                                 Friday = bs.Friday,
                                 Saturday = bs.Saturday,
                                 Sunday = bs.Sunday
                             }).ToList();
                foreach (var q in query)
                {
                    //根据时间段判断一次
                    DateTime tempSt = DateTime.Parse(startDate + " " + startTime);
                    DateTime tempEt = DateTime.Parse(startDate + " " + endTime);
                    DateTime tempQST = DateTime.Parse(startDate + " " + q.sst);
                    DateTime tempQET = DateTime.Parse(startDate + " " + q.set);
                    if (tempSt >= tempQET || tempEt < tempQST)
                    {
                        continue;
                    }
                    else
                    {
                        if (q.ssd > ed)//开始日期晚于本次会议结束日期，不会冲突
                        {
                            continue;
                        }
                        else
                        {
                            if (sd.DayOfWeek.ToString() == "Monday")
                            {
                                if (q.Monday.HasValue)
                                    if (q.Monday.Value)
                                        return "系统检测到与已存在周一的预定发生冲突";
                            }
                            else if (sd.DayOfWeek.ToString() == "Tuesday" && q.Tuesday.HasValue ? q.Tuesday.Value : false) { return "系统检测到与已存在周二的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Wednesday" && q.Wednesday.HasValue ? q.Wednesday.Value : false) { return "系统检测到与已存在周三的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Thursday" && q.Thursday.HasValue ? q.Thursday.Value : false) { return "系统检测到与已存在周四的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Friday" && q.Friday.HasValue ? q.Friday.Value : false) { return "系统检测到与已存在周五的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Saturday" && q.Saturday.HasValue ? q.Saturday.Value : false) { return "系统检测到与已存在周六的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Sunday" && q.Sunday.HasValue ? q.Sunday.Value : false) { return "系统检测到与已存在周末的预定发生冲突"; }
                        }
                    }
                }
            }
            return "";
        }


        public string checkPeriodicConflict(int meetingRoomNo, string startDate, string startTime,
           string weekday, string endDate, string endTime)
        {
            string[] weekdays = weekday.Split(',');//拆分星期
            DateTime sd = DateTime.Parse(startDate);
            DateTime ed = DateTime.Parse(endDate);

            using (var mme = new VenueBookingTestEntities())
            {
                //查询出所有的在本次会议开始后才结束的会议预定
                var query = (from bm in mme.MTR_bas_BookingManage
                             join bs in mme.MTR_bas_BookingSchedul
                                 on bm.bookingID equals bs.planId
                             where bm.Meetingroom == meetingRoomNo && (bm.bookingState == 1 || bm.bookingState == 2) && bs.isPeriodic == true
                             && bs.meetingEndDate >= sd
                             select new
                             {
                                 ssd = bs.meetingStartDate,
                                 sst = bs.startTime,
                                 sed = bs.meetingEndDate,
                                 set = bs.endTime,
                                 Monday = bs.Monday,
                                 Tuesday = bs.Tuesday,
                                 Wednesday = bs.Wednesday,
                                 Thursday = bs.Thursday,
                                 Friday = bs.Friday,
                                 Saturday = bs.Saturday,
                                 Sunday = bs.Sunday
                             }).ToList();
                foreach (var q in query)
                {
                    //根据时间段判断一次
                    DateTime tempSt = DateTime.Parse(startDate + " " + startTime);
                    DateTime tempEt = DateTime.Parse(startDate + " " + endTime);
                    DateTime tempQST = DateTime.Parse(startDate + " " + q.sst);
                    DateTime tempQET = DateTime.Parse(startDate + " " + q.set);
                    if (tempSt >= tempQET || tempEt < tempQST)
                    {
                        return "";
                    }
                    else
                    {
                        if (q.ssd > ed)
                        {//开始日期晚于本次会议结束日期，不会冲突
                            return "";
                        }
                        if (q.ssd <= sd)  //sd 到q.sed会有冲突
                        {
                            do
                            {
                                string dow = sd.DayOfWeek.ToString();
                                for (int i = 0; i < weekdays.Length; i++)
                                {
                                    if (dow == weekdays[i]) //传入的记录中有这个
                                    {
                                        if (dow == "Monday" && q.Monday.Value) { return "系统检测到与已存在周一的预定发生冲突"; }
                                        else if (dow == "Tuesday" && q.Tuesday.Value) { return "系统检测到与已存在周二的预定发生冲突"; }
                                        else if (dow == "Wednesday" && q.Wednesday.Value) { return "系统检测到与已存在周三的预定发生冲突"; }
                                        else if (dow == "Thursday" && q.Thursday.Value) { return "系统检测到与已存在周四的预定发生冲突"; }
                                        else if (dow == "Friday" && q.Friday.Value) { return "系统检测到与已存在周五的预定发生冲突"; }
                                        else if (dow == "Saturday" && q.Saturday.Value) { return "系统检测到与已存在周六的预定发生冲突"; }
                                        else if (dow == "Sunday" && q.Sunday.Value) { return "系统检测到与已存在周末的预定发生冲突"; }
                                    }
                                }
                                sd.AddDays(1);
                            }
                            while (sd > q.sed);
                        }
                        if (q.ssd > sd)
                        {
                            //q.ssd到q.sed会有冲突
                            do
                            {
                                string dow = q.ssd.Value.DayOfWeek.ToString();
                                for (int i = 0; i < weekdays.Length; i++)
                                {
                                    if (dow == weekdays[i]) //传入的记录中有这个
                                    {
                                        if (dow == "Monday" && q.Monday.Value) { return "系统检测到与已存在周一的预定发生冲突"; }
                                        else if (dow == "Tuesday" && q.Tuesday.Value) { return "系统检测到与已存在周二的预定发生冲突"; }
                                        else if (dow == "Wednesday" && q.Wednesday.Value) { return "系统检测到与已存在周三的预定发生冲突"; }
                                        else if (dow == "Thursday" && q.Thursday.Value) { return "系统检测到与已存在周四的预定发生冲突"; }
                                        else if (dow == "Friday" && q.Friday.Value) { return "系统检测到与已存在周五的预定发生冲突"; }
                                        else if (dow == "Saturday" && q.Saturday.Value) { return "系统检测到与已存在周六的预定发生冲突"; }
                                        else if (dow == "Sunday" && q.Sunday.Value) { return "系统检测到与已存在周末的预定发生冲突"; }
                                    }
                                }
                                q.ssd.Value.AddDays(1);
                            }
                            while (q.ssd.Value > q.sed.Value);
                        }
                        if (q.sed >= ed)
                        {
                            //q.ssd到ed会有冲突
                            do
                            {
                                string dow = q.ssd.Value.DayOfWeek.ToString();
                                for (int i = 0; i < weekdays.Length; i++)
                                {
                                    if (dow == weekdays[i]) //传入的记录中有这个
                                    {
                                        if (dow == "Monday" && q.Monday.Value) { return "系统检测到与已存在周一的预定发生冲突"; }
                                        else if (dow == "Tuesday" && q.Tuesday.Value) { return "系统检测到与已存在周二的预定发生冲突"; }
                                        else if (dow == "Wednesday" && q.Wednesday.Value) { return "系统检测到与已存在周三的预定发生冲突"; }
                                        else if (dow == "Thursday" && q.Thursday.Value) { return "系统检测到与已存在周四的预定发生冲突"; }
                                        else if (dow == "Friday" && q.Friday.Value) { return "系统检测到与已存在周五的预定发生冲突"; }
                                        else if (dow == "Saturday" && q.Saturday.Value) { return "系统检测到与已存在周六的预定发生冲突"; }
                                        else if (dow == "Sunday" && q.Sunday.Value) { return "系统检测到与已存在周末的预定发生冲突"; }
                                    }
                                }
                                q.ssd.Value.AddDays(1);
                            }
                            while (q.ssd.Value > ed);
                        }
                    }
                }
            }
            return "";
        }




        public List<MtrData> Seek(DateTime date, string type, string address,
            string isVIP, string userName, string orgType1, string orgType3, string capacity)
        {
            //createmeeting();   
            List<MtrData> listMtrData = new List<MtrData>();
            int cap = Convert.ToInt32(capacity);
            var mtr_resEn = new VenueBookingTestEntities();
            var query = (from a in mtr_resEn.MTR_bas_Meetingroom
                         where a.mtrDelete == true && a.mtrCapacity >= cap && a.type == type
                         && a.mtrAddress == address
                         && a.mtrCompanyRuc == orgType1
                         && (a.mtrDeptRuc == "所有部门" || a.mtrDeptRuc == orgType3)
                         select new
                         {
                             mtrID = a.mtrId,
                             mtrName = a.mtrName,
                             mtrCompanyRuc = a.mtrCompanyRuc,
                             mtrDeptRuc = a.mtrDeptRuc,
                             mtrAddress = a.mtrAddress,
                             mtrAddress1 = a.mtrAddress1,
                             type = a.type,
                             mtrCapacity = a.mtrCapacity,
                             mtrPhone = a.mtrPhone,
                             mtrPhoto = a.mtrPhoto,
                             mtrType = a.mtrType,
                             mtrFreeTime = a.mtrFreeTime,
                             mtrState = a.mtrState,
                             mtrLongestBookingDay = a.mtrLongestBookingDay,
                             mtrLongestAdvanceBookingTime = a.mtrLongestAdvanceBookingTime,
                             mtrLastUser = a.mtrLastUser,
                             mtrLastTime = a.mtrLastTime
                         }).ToList();
            if (isVIP != string.Empty)
            {
                query = query.Where(p => p.mtrType==isVIP).ToList();
            }
            //query 是符合条件的会议室
            MtrData md = new MtrData();
            foreach (var vq in query)
            {
                md = new MtrData();
                md.mtrId = vq.mtrID;
                md.mtrName = vq.mtrName;
                md.mtrCompanyRuc = vq.mtrCompanyRuc;
                md.mtrDeptRuc = vq.mtrDeptRuc;
                md.mtrAddress = vq.mtrAddress;
                md.mtrAddress1 = vq.mtrAddress1;
                md.mtrCapacity = vq.mtrCapacity;
                md.mtrPhone = vq.mtrPhone;
                md.mtrPhoto = vq.mtrPhoto;
                md.mtrType = vq.mtrType;
                md.mtrFreeTime = vq.mtrFreeTime;
                md.mtrState = vq.mtrState;
                md.mtrLongestBookingDay = vq.mtrLongestBookingDay;
                md.mtrLongestAdvanceBookingTime = vq.mtrLongestAdvanceBookingTime == 0 ? "" : vq.mtrLongestAdvanceBookingTime.ToString();//.ToString();
                md.mtrLastUser = vq.mtrLastUser;
                md.mtrLastTime = vq.mtrLastTime;
                var vk = (from k in mtr_resEn.MTR_bas_MeetingroomResources
                          join l in mtr_resEn.MTR_bas_Resources
                          on k.resId equals l.resId
                          where k.mtrId == vq.mtrID
                          select new
                          {
                              resId = k.resId,
                              resName = l.resName,
                              resIcon = l.resIcon
                          }).ToList();

                md.listMtrRes = new List<MtrRes>();
                foreach (var vks in vk)
                {
                    md.listMtrRes.Add(new MtrRes() { resId = vks.resId, resName = vks.resName, resIcon = vks.resIcon });
                }
                DateTime ds = date.AddDays(4);
                var vme = (from bm in mtr_resEn.MTR_bas_BookingManage
                           join vim in mtr_resEn.booking_View
                               on bm.bookingID equals vim.bookingID
                           where bm.Meetingroom == vq.mtrID && vim.meetingEndDate >= date && vim.meetingStartDate <= ds
                           //取消对于时间的判断&& bm.startTime >= DateTime.Now
                           select new
                           {
                               bookingID = bm.bookingID,
                               bookingType = bm.bookingType,
                               Meetingroom = bm.Meetingroom,
                               bookingPerson = bm.bookingPerson,
                               bookingTime = bm.bookingTime,
                               //endTime = bm.endTime,
                               meetingTheme = bm.meetingTheme,
                               participants = bm.participants,
                               meetingAbstract = bm.meetingAbstract,
                               specialRequestFirst = bm.specialRequestFirst,
                               specialRequestSecond = bm.specialRequestSecond,
                               bookingState = bm.bookingState,
                               cancelTime = bm.cancelTime,
                               cancelReason = bm.cancelReason,
                               useResult = bm.useResult,
                               undefine1 = bm.undefine1
                           }).ToList();
                md.listMtrEvent = new List<MtrEvent>();
                foreach (var vm in vme)
                {
                    var bs = (from bookScu in mtr_resEn.MTR_bas_BookingSchedul
                              where vm.bookingID == bookScu.planId
                              select new
                              {
                                  planId = bookScu.planId,
                                  meetingRoom = bookScu.meetingRoom,
                                  meetingStartDate = bookScu.meetingStartDate,
                                  startTime = bookScu.startTime,
                                  meetingEndDate = bookScu.meetingEndDate,
                                  endTime = bookScu.endTime,
                                  Monday = bookScu.Monday,
                                  Tuesday = bookScu.Tuesday,
                                  Wednesday = bookScu.Wednesday,
                                  Thursday = bookScu.Thursday,
                                  Friday = bookScu.Friday,
                                  Saturday = bookScu.Saturday,
                                  Sunday = bookScu.Sunday,
                                  isPeriodic = bookScu.isPeriodic,
                                  undefine1 = bookScu.undefine1,
                                  undefine2 = bookScu.undefine2
                              });
                    md.listMtrEvent.Add(new MtrEvent()
                    {
                        bookingID = vm.bookingID,
                        bookingType = vm.bookingType,
                        Meetingroom = vm.Meetingroom,
                        bookingPerson = vm.bookingPerson,
                        startTime = Convert.ToDateTime(vm.bookingTime),  //修改日期2013-9-12 15:12
                        //endTime = Convert.ToDateTime(vm.endTime),
                        meetingTheme = vm.meetingTheme,
                        participants = vm.participants,
                        meetingAbstract = vm.meetingAbstract,
                        specialRequestFirst = vm.specialRequestFirst,
                        specialRequestSecond = vm.specialRequestSecond,
                        bookingState = vm.bookingState,
                        cancelTime = vm.cancelTime,
                        cancelReason = vm.cancelReason,
                        useResult = vm.useResult,
                        BookingSchedul = bs,
                        undefine1 = vm.undefine1
                    });
                }
                listMtrData.Add(md);
            }

            return listMtrData;
        }

        public string PeriodicLock(int meetingRoomNo, string startDate, string startTime,
            string endDate, string endTime, string weeks, string bookingPerson,string orgType1,string orgType3)
        {
            string otp = checkOnceConflict(meetingRoomNo, startDate, startTime, weeks, endDate, endTime);
            string ptp = checkPeriodicConflict(meetingRoomNo, startDate, startTime, weeks, endDate, endTime);
            if (otp.Length > 1 || ptp.Length > 1) return otp + ptp;
            try
            {
                //using (var mtr_BookingSuc = new meetingroomManagementEntities())
                //{
                MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                string keyId = Guid.NewGuid().ToString();
                string[] weekdays = weeks.Split(',');
                mtrBS.isPeriodic = true;
                mtrBM.bookingID = keyId;
                mtrBM.bookingType = "管理员锁定";
                mtrBM.Meetingroom = meetingRoomNo;
                mtrBM.bookingPerson = bookingPerson;
                mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                mtrBM.meetingTheme = "";
                mtrBM.participants = "";
                mtrBM.meetingAbstract = "";
                mtrBM.specialRequestFirst = "";
                mtrBM.specialRequestSecond = "";
                mtrBM.bookingState = 2;//状态为预定成功
                mtrBM.undefine1 =orgType1;
                mtrBM.undefine2 = orgType3;
                mtrBM.useResult = 0;
                new BaseRepositoryBLL<MTR_bas_BookingManage>().AddEntities(mtrBM);
                //mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                //mtr_BookingSuc.SaveChanges();
                foreach (string weekday in weekdays)
                {
                    //mtrBS.(weekday.ToString())=weekday;
                    if (weekday == "Monday") mtrBS.Monday = true;
                    else if (weekday == "Tuesday") mtrBS.Tuesday = true;
                    else if (weekday == "Wednesday") mtrBS.Wednesday = true;
                    else if (weekday == "Thursday") mtrBS.Thursday = true;
                    else if (weekday == "Friday") mtrBS.Friday = true;
                    else if (weekday == "Saturday") mtrBS.Saturday = true;
                    else if (weekday == "Sunday") mtrBS.Sunday = true;
                }
                mtrBS.planId = keyId;
                mtrBS.meetingRoom = meetingRoomNo;
                mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                mtrBS.startTime = startTime;
                mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                mtrBS.endTime = endTime;
                mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                //mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);
                //mtr_BookingSuc.SaveChanges();
                new BaseRepositoryBLL<MTR_bas_BookingSchedul>().AddEntities(mtrBS);
                //}
                return "锁定成功";
            }
            catch (Exception ex)
            {
                Worker.writeErrorMessage("0", ex, bookingPerson);
                return ex.Message;
            }
        }

        public string OnetimeLock(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime,string userName,
            string orgType1, string orgType3)
        {
            MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
            MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
            string keyId = Guid.NewGuid().ToString();
            //单次锁定
            mtrBS.isPeriodic = false;
            mtrBM.bookingID = keyId;
            mtrBM.bookingType = "管理员锁定";
            mtrBM.Meetingroom = meetingRoomNo;
            mtrBM.bookingPerson = userName;
            mtrBM.bookingTime = DateTime.Now;  //保存预定时间
            mtrBM.meetingTheme = "lock";
            mtrBM.participants = "";
            mtrBM.meetingAbstract = "";
            mtrBM.specialRequestFirst = "";
            mtrBM.specialRequestSecond = "";
            mtrBM.bookingState = 3;
            mtrBM.undefine1 = orgType1;
            mtrBM.undefine2 = orgType3;
            mtrBM.undefine3 = null;
            mtrBM.useResult = 0;
            //mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
            new BaseRepositoryBLL<MTR_bas_BookingManage>().AddEntities(mtrBM);
            mtrBS.Monday = null;
            mtrBS.Tuesday = null;
            mtrBS.Wednesday = null;
            mtrBS.Thursday = null;
            mtrBS.Friday = null;
            mtrBS.Saturday = null;
            mtrBS.Sunday = null;
            mtrBS.undefine3 = "";
            mtrBS.planId = keyId;
            mtrBS.meetingRoom = meetingRoomNo;
            mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
            mtrBS.startTime = startTime;
            mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
            mtrBS.endTime = endTime;
            mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
            new BaseRepositoryBLL<MTR_bas_BookingSchedul>().AddEntities(mtrBS);

            return "锁定成功";
        }

        public string SelfBookingSuccess(string participants, string cc, string meetingTheme, string meetingAbstract, string phoneNo,
           string mtrAdd, int mtrNo, string specialRequestFirst, string specialRequestSecond, DateTime st, DateTime et,
           string startDate, string startTime, string endDate, string endTime, string userName, string weeks, string orgType1, string orgType3)
        {
            try
            {

                MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                string keyId = Guid.NewGuid().ToString();
                string[] weekdays = weeks.Split(',');
                //单次自助预定
                if (weekdays.Length <= 1)
                {
                    mtrBS.isPeriodic = false;
                    mtrBM.bookingID = keyId;
                    mtrBM.bookingType = "自助";
                    mtrBM.Meetingroom = mtrNo;
                    mtrBM.bookingPerson = userName;
                    mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                    mtrBM.meetingTheme = meetingTheme;
                    mtrBM.participants = participants;
                    mtrBM.meetingAbstract = meetingAbstract;
                    mtrBM.specialRequestFirst = specialRequestFirst;
                    mtrBM.specialRequestSecond = specialRequestSecond;
                    mtrBM.bookingState = 2;
                    mtrBM.undefine1 = orgType1;
                    mtrBM.undefine2 = orgType3;
                    mtrBM.undefine3 = "0";
                    mtrBM.useResult = 0;
                    new BaseRepositoryBLL<MTR_bas_BookingManage>().AddEntities(mtrBM);
                    //mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                    mtrBS.Monday = false;
                    mtrBS.Tuesday = false;
                    mtrBS.Wednesday = false;
                    mtrBS.Thursday = false;
                    mtrBS.Friday = false;
                    mtrBS.Saturday = false;
                    mtrBS.Sunday = false;
                    mtrBS.planId = keyId;
                    mtrBS.meetingRoom = mtrNo;
                    mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                    mtrBS.startTime = startTime;
                    mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                    mtrBS.endTime = endTime;
                    mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                    mtrBS.undefine2 = phoneNo;
                    mtrBS.undefine3 = cc;
                    new BaseRepositoryBLL<MTR_bas_BookingSchedul>().AddEntities(mtrBS);
                    string[] attendees = participants.Split(';');
                    string[] ccs = cc.Split(';');
                    emailSrv e = new emailSrv();
                    string body = meetingAbstract;

                    int che =  new BaseRepositoryBLL<MTR_bas_BookingManage>().LoadEntities(p => p.bookingID.Equals(keyId)).ToList().Count;
                    if (che == 1)
                    {
                        e.SendMeetingRequest(st, et, mtrAdd, meetingTheme, body, attendees, ccs,
                            keyId, false, userName, userName + "@kaifa.cn", false, "");
                    }
                    else
                    {
                        //string insertSQL = "insert into [VenueBooking].[dbo].[MTR_bas_BookingManage] ";
                    }
                }
                return "恭喜您，自助预定成功";
            }
            catch (Exception e)
            {
                Worker.writeErrorMessage("0", e, userName);
                return e.Message;
            }
        }

        public string checkOnceConflict(int mtrNo, string startDate, string startTime, string weeks, string endDate, string endTime)
        {
            string[] weekdays = weeks.Split(',');//拆分星期
            DateTime sd = DateTime.Parse(startDate);
            DateTime ed = DateTime.Parse(endDate);
            using (VenueBookingTestEntities mme = new VenueBookingTestEntities())
            {
                //查询出所有的在本次会议开始后才结束的单次会议预定
                var query = (from bm in mme.MTR_bas_BookingManage
                             join bs in mme.MTR_bas_BookingSchedul
                                 on bm.bookingID equals bs.planId
                             where bm.Meetingroom == mtrNo && (bm.bookingState == 1 || bm.bookingState == 2) && bs.isPeriodic == false
                             && bs.meetingEndDate >= sd
                             //((sd <= bs.meetingStartDate && bs.meetingStartDate <= ed) || (sd >= bs.meetingStartDate && ed <= bs.meetingEndDate) || (sd <= bs.meetingEndDate && bs.meetingEndDate <= ed))
                             select new
                             {
                                 ssd = bs.meetingStartDate,
                                 sst = bs.startTime,
                                 sed = bs.meetingEndDate,
                                 set = bs.endTime,
                             }).ToList();
                foreach (var q in query)
                {
                    //根据时间段判断一次
                    DateTime tempSt = DateTime.Parse(startDate + " " + startTime);
                    DateTime tempEt = DateTime.Parse(startDate + " " + endTime);
                    DateTime tempQST = DateTime.Parse(startDate + " " + q.sst);
                    DateTime tempQET = DateTime.Parse(startDate + " " + q.set);
                    if (tempSt >= tempQET || tempEt < tempQST)
                    {
                        return "";
                    }
                    else
                    {
                        string dow = q.ssd.Value.DayOfWeek.ToString();//已有事件的星期
                        for (int i = 0; i < weekdays.Length; i++)
                        {
                            if (dow == weekdays[i]) { return "系统检测到与已存在" + weekdays[i] + "的预定发生冲突"; }
                        }
                    }
                }
            }
            return "";
        }

      


        /// <summary>
        /// 字符串转成时间 计算时间差
        /// </summary>
        /// <param name="st">st 开始时间的字符串形式 yyyy-MM-dd hh-mm-ss</param>
        /// <param name="et">et 结束时间的字符串形式 yyyy-MM-dd hh-mm-ss</param>
        /// <returns>dateDiff 返回的字符串类型</returns>
        public string timeDiffer(string st, string et)
        {
            DateTime sst = DateTime.Parse(st);
            DateTime eet = DateTime.Parse(et);
            //if(startDate==endDate && ){}
            string dateDiff = null;
            TimeSpan ts1 = new TimeSpan(sst.Ticks);
            TimeSpan ts2 = new TimeSpan(eet.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            //显示时间  
            dateDiff = ts.Days.ToString() + "天"
                    + ts.Hours.ToString() + "小时"
                    + ts.Minutes.ToString() + "分钟"
                    + ts.Seconds.ToString() + "秒";
            return dateDiff;
        }



    }
}
